<template>
  <el-form
    class="supplier-info-form"
    :ref="refName"
    :rules="formRules"
    :model="formData"
    :inline="isInline"
    :disabled="readonly"
    :label-width="labelWidth"
    :label-suffix="labelSuffix"
    :validate-on-rule-change="false"
    :hide-required-asterisk="readonly"
    :show-message="showMessage && !readonly"
  >
    <el-row class="number-input-align-left">
      <el-col :span="field.colSpan || (24 / colNumOfRow)"
        v-for="(field, index) in formFields"
        :key="index">
        <el-form-item
          :class="operationObj(field.prop)?'highlight':''"
          :prop="field.prop"
          :label="field.label"
          :label-width="field.width || formItemWidth"
          :required="field.required"
        >
          <!-- 普通下拉框 -->
          <template v-if="field.type === 'select'">
            <el-select
              v-model="formData[field.prop]"
              style="width: 100%"
              :multiple="field.multiple"
              :filterable="field.filterable"
              :filter-method="field.filterMethod"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :disabled="field.disabled"
              :clearable="field.clearable"
              @change="(data)=>{handleFieldChanged(data, field)}"
              :collapse-tags="field.collapseTags === false ? false : true"
            >
              <template v-if="field.options && field.options.length">
                <el-option
                  v-for="(option, key) in field.options"
                  :key="key"
                  :label="option.label"
                  :value="option.value"
                  :disabled="option.value === 0 || (field.disabledValues && field.disabledValues.includes(option.value))"
                />
              </template>
              <template v-else-if="field.dict">
                <el-option
                  v-for="(option, key) in dictOptData[field.dict]"
                  :key="key"
                  :label="option.label"
                  :value="option.value"
                  :disabled="option.value === 0 || (field.disabledValues && field.disabledValues.includes(option.value)) || option.disable==0"
                />
              </template>
              <template v-else-if="field.sysDict">
                <el-option
                  v-for="(option, key) in sysDictOptData[field.sysDict]"
                  :key="key"
                  :label="option.label"
                  :value="option.value"
                  :disabled="option.value === 0 || (field.disabledValues && field.disabledValues.includes(option.value))"
                />
              </template>
            </el-select>
          </template>
          <!-- 主营品类 -->
          <template v-else-if="field.type === 'categorySelect'">
            <CategorySelect ref="categorySelect"
              v-model="formData[field.prop]"
              :disabled="field.disabled || readonly"
              @onSelected="(data)=>{handleCategorySelect(data, field)}" :setName="true"/>
          </template>
          <!-- 用户中心用户信息 -->
          <template v-else-if="field.type === 'userSelect'">
            <UserSelect style="width: 100%" ref="userSelect"
              v-model="formData[field.prop]"
              :userName="formData[`${field.prop}Name`]"
              :disabled="field.disabled"
              :placeholder="field.placeholder || `请输入${field.label}`"
              @onSelected="(data)=>{handleUserSelect(data, field)}" />
          </template>
          <!-- 管理区域 -->
          <template v-else-if="field.type === 'managementArea'">
            <ManagementAreaSelect
              style="width: 100%"
              ref="managementArea"
              v-model="formData[field.prop]"
              :disabled="field.disabled || readonly"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :multiple="field.multiple"
              :defaultValue="field.defaultValue"
              :hrAreaId="field.hrAreaId"
              :hiddenKeys="field.hiddenKeys"
              @onSelected="(data)=>{handleManagementAreaSelect(data, field)}" />
          </template>
          <!-- 省份选择 -->
          <template v-else-if="field.type === 'provinceSelect'">
            <ProvinceSelect
              style="width: 100%"
              ref="province"
              v-model="formData[field.prop]"
              :disabled="field.disabled || readonly"
              :placeholder="field.placeholder || `请选择${field.label}`"
              :multiple="field.multiple"
              @onSelected="(data)=>{handleProvinceSelect(data, field)}" />
          </template>
          <!-- 品牌选择 -->
          <template v-else-if="field.type === 'brandSelect'">
            <el-input
              readonly
              v-model="formData[field.prop]"
              :title="formData[field.prop]"
              :disabled="field.disabled"
              :placeholder="field.placeholder || `请选择${field.label}`"
              @focus="brandDialog.visible = true"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                :disabled="field.disabled"
                @click="brandDialog.visible = true"
              ></el-button>
            </el-input>
          </template>
          <!-- 日期选择 -->
          <template v-else-if="field.type === 'date' || field.type === 'datetime'">
            <el-date-picker
              style="width: 100%"
              v-model="formData[field.prop]"
              :title="formData[field.prop]"
              :value-format="field.type === 'date'?'yyyy-MM-dd':'yyyy-MM-dd HH:mm:ss'"
              :type="field.type"
              :disabled="field.disabled"
              :placeholder="field.placeholder || `请选择${field.label}`"
              @change="(data)=>{handleFieldChanged(data, field)}" />
          </template>
          <!-- 文件输入框 -->
          <template v-else-if="field.type === 'annex'">
            <span v-if="formData[field.prop]">
              <AnnexDownloadButton
                v-model.trim="formData[field.prop]"
                :fileName="field.fileName || field.label" />
              <el-tooltip effect="dark" content="删除" v-if="!field.disabled && !readonly">
                <i class="delete-icon el-icon-close" @click="handleDelteAnnex(field.prop)"></i>
              </el-tooltip>
            </span>
            <AnnexUploadButton v-else
              v-model="formData[field.prop]"
              :typeList="field.typeList"
              @onUploaded="(params)=>{handleUploaded(params, field)}" />
          </template>
          <!-- 数字输入框 -->
          <template v-else-if="field.type === 'number'">
            <el-input-number
              style="width: 100%"
              :controls="false"
              controls-position="right"
              v-model.trim="formData[field.prop]"
              :title="formData[field.prop]"
              :max="field.max" :min="field.min"
              :precision="field.precision"
              :disabled="field.disabled"
              :placeholder="field.placeholder || `请输入${field.label}`"
              @change="(data)=>{handleFieldChanged(data, field)}" />
          </template>
          <!-- 自定义数字输入框 -->
          <template v-else-if="field.type === 'inputNum'">
            <InputNumber
              style="width: 100%"
              :controls="false"
              v-model.trim="formData[field.prop]"
              :title="formData[field.prop]"
              :max="field.max"
              :min="field.min"
              :precision="field.precision"
              :disabled="field.disabled"
              :placeholder="field.placeholder || `请输入${field.label}`"
              @change="(data)=>{handleFieldChanged(data, field)}"
            />
          </template>
          <!-- 普通输入框 -->
          <template v-else-if="field.type === 'textarea'">
            <el-input
              v-model.trim="formData[field.prop]"
              :title="formData[field.prop]"
              :placeholder="field.placeholder || `请输入${field.label}`"
              type="textarea"
              :autosize="{ minRows: 1}"
              :disabled="field.disabled"
              @change="(data)=>{handleFieldChanged(data, field)}" />
          </template>
          <!-- 文本按钮 -->
          <template v-else-if="field.type === 'button'">
            <el-row type="flex">
              <template  v-for="item in field.buttonList" >
                <a :key="item.key"
                  v-if="!readonly || (readonly && item.key === 'view')"
                  :type="item.type || 'text'"
                  @click="handleClickButton(item, field)"
                  style="margin-right: 8px"
                >{{ item.label }}</a>
              </template>
            </el-row>
          </template>
          <!-- 普通输入框 -->
          <template v-else>
            <el-input
              v-model.trim="formData[field.prop]"
              :title="formData[field.prop]"
              :placeholder="field.placeholder || `请输入${field.label}`"
              :disabled="field.disabled"
              :maxlength="field.maxlength"
              :minlength="field.minlength"
              @change="(data)=>{handleFieldChanged(data, field)}" />
          </template>
          <span class="highlight-hint" v-if="operationObj(field.prop)">
            原字段参数: {{operationObj(field.prop)['fieldValueOld']}}
          </span>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- <pre>{{formItemData}}</pre> -->
    <BusinessCategoryDialog
      :visible.sync="businessCategory.visible"
      :categoryUuids="(formData.manageCategory || []).map(item => item.categoryUuid)"
      @getCheckedCategory="getCheckedCategory"
    />
    <basic-dialog
      title="已选经营品类"
      :visible.sync="viewDialog.visible"
      :showFooter="false"
      :handleClose="handleColseDialog"
    >
      <ShowCategoryTags
        class="show_category_tags_wrap"
        :dataSource="formData.manageCategory"
      />
    </basic-dialog>
    <BrandSelect
      title="选择合作品牌"
      :dialogVisible.sync="brandDialog.visible"
      :brandList="brandDialog.list"
      @handle-select="handleBrandSelect"
    />
  </el-form>
</template>

<script>
import { mapState } from 'vuex';
import UserSelect from '@/components/supplier/UserRemoteSelect'
import CategorySelect from '@/pages/supplier/components/SelectMainCategory'
import AnnexUploadButton from '@/pages/supplier/components/annexUploadButton' // 上传附件按钮
import AnnexDownloadButton from '@/pages/supplier/components/annexDownloadButton' // 下载附件按钮
import ManagementAreaSelect from '@/components/supplier/ManagementAreaSelect'
import ProvinceSelect from '@/components/supplier/ProvinceSelect'
import BrandSelect from '@/components/supplier/BrandSelect'
import BasicDialog from '@/components/BasicDialog';
import BusinessCategoryDialog from '@/components/supplier/BusinessCategoryDialog';
import ShowCategoryTags from '@/components/supplier/BusinessCategoryDialog/ShowCategoryTags';
import { getTimeStamp } from '@supplier/utils';
import InputNumber from '@/components/inputNumber/inputNumber'

export default {
  props: {
    refName: { type: String, default: 'supplierInfoForm' }, // 表单ref名
    dataSource: { type: Object, default () { return {} } }, // 表单formData
    rules: { type: Object, default () { return {} } }, // 	表单验证规则
    isInline: { type: Boolean, default: false }, // 表单是否开启inline模式
    readonly: { type: Boolean, default: false }, // 表单是否开启禁用
    colNumOfRow: { type: Number, default: 3 }, // 表单每行col数量
    formItemWidth: { type: String, default: '200px' }, // 表单item默认宽度
    formFields: { type: Array, default () { return [] } }, // 表单项集合
    labelWidth: { type: String, default: '140px' }, // 表单域标签的宽度
    labelSuffix: { type: String, default: '' }, // 表单域标签的后缀
    showMessage: { type: Boolean, default: true }, // 表单是否开启禁用
    operation: { type: Array, default () { return [] } }, // 新旧对比字段
  },
  components: {
    UserSelect,
    CategorySelect,
    AnnexUploadButton,
    AnnexDownloadButton,
    ManagementAreaSelect,
    ProvinceSelect,
    BrandSelect,
    BusinessCategoryDialog,
    BasicDialog,
    ShowCategoryTags,
    InputNumber
  },
  data () {
    return {
      valid: true,
      businessCategory: {
        visible: false
      },
      viewDialog: {
        visible: false,
        list: []
      },
      brandDialog: {
        visible: false,
        list: []
      }
    };
  },
  watch: {
    rules: {
      handler (newVal) {
        if (newVal) {
          this.clearValidate()
        }
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    ...mapState('supplier/dict', [
      'dictOptData',
      'sysDictOptData',
    ]),
    ...mapState('supplier/manageArea', [
      'manageArea',
    ]),
    formData () {
      return this.dataSource
    },
    formRules () {
      return this.readonly ? {} : this.rules
    },
    formItemData () {
      const obj = {}
      this.formFields.forEach((field) => {
        obj[field.prop] = this.dataSource[field.prop]
      })
      return obj
    },
  },
  mounted () {
    const { cooperativeBrandArr: brandArr = [] } = this.dataSource
    if (brandArr && brandArr.length) {
      this.brandDialog.list = brandArr
    }
  },
  methods: {
    clearValidate () {
      if (this.refName && this.$refs[this.refName]) {
        this.$refs[this.refName].clearValidate && this.$refs[this.refName].clearValidate()
      }
    },
    handleFieldChanged (value, field) {
      // 校验合同开始、结束时间
      const { contractStartTime, contractEndTime } = this.formData;
      if (field.prop == 'contractStartTime' && value && contractEndTime && (getTimeStamp(value) > getTimeStamp(contractEndTime))) {
        this.formData.contractStartTime = ''
        return this.$message.warning('合同开始时间不能大于合同结束时间')
      }
      if (field.prop == 'contractEndTime' && value && contractStartTime && (getTimeStamp(value) < getTimeStamp(contractStartTime))) {
        this.formData.contractEndTime = ''
        return this.$message.warning('合同结束时间不能小于合同开始时间')
      }
      this.$emit('change', { value, ...field })
      this.$emit('dataSource:update', this.formData)
    },
    // 上传关系证明
    handleUploaded ({ response, file }, field) {
      this.handleFieldChanged({ response, file }, field)
    },
    // 删除附件
    handleDelteAnnex (prop) {
      this.formData[prop] = ''
    },
    handleCategorySelect (data, field) {
      this.handleFieldChanged(data, field)
      if (field.prop === 'mainCategory') {
        if (this.formData.hasOwnProperty('mainCategoryCode')) {
          this.formData.mainCategory = data.categoryName
          this.formData.mainCategoryCode = data.categoryNo
          this.formData.mainCategoryId = data.uuid
        }
        if (this.formData.hasOwnProperty('metal')) {
          this.formData.metal = parseInt(data.isMetal, 10)
        }
      }
    },
    handleUserSelect (data, field) {
      this.handleFieldChanged(data, field)
      if (field.prop === 'businessContact') {
        if (!data || !data.userId) {
          this.formData[`businessContact`] = undefined
        }
        if (this.formData.hasOwnProperty(`businessContactName`)) {
          if (data && data.userName) {
            this.formData[`businessContactName`] = data.userName
          } else {
            this.formData[`businessContactName`] = ''
          }
        }
      }
      // 赋值供应商管理区域
      if (data?.hrAreaId) {
        this.formData.managementAreaId = this.manageArea.find(item => item.hrAreaId == data.hrAreaId).manageAreaId
      }
    },
    handleManagementAreaSelect (data, field) {
      this.handleFieldChanged(data, field)
      if (field.multiple) {
        // 多选
      } else {
        if (!data) {
          this.formData[field.prop] = undefined
          return
        }
        if (field.prop === 'managementAreaId') {
          this.formData[`managementAreaName`] = data.manageAreaName
        }
      }
    },
    handleProvinceSelect (data, field) {
      this.handleFieldChanged(data, field)
      // console.log('handleProvinceSelect', { data, field })
    },
    handleBrandSelect ({ row: data, type }) {
      // console.log(`handleBrandSelect :>> type: ${type}`, JSON.stringify(data))
      const prop = 'cooperativeBrand'
      let arr = this.formData[`${prop}Arr`] || []
      if (type === 'select') {
        const obj = { brandId: data.uuid, brandName: data.brandName, }
        this.brandDialog.list.push(obj)
        arr.push(obj)
      } else if (type === 'cancel') {
        this.brandDialog.list = this.brandDialog.list.filter(i => i.brandId != data.uuid)
        arr = arr.filter(i => i.brandId != data.uuid)
      }
      let map = new Map();
      for (let item of arr) {
        if (!map.has(item.brandId)) {
          map.set(item.brandId, item);
        };
      };
      const brandArr = [...map.values()]
      this.formData[`${prop}Arr`] = brandArr
      this.formData[prop] = brandArr.map(i => i.brandName).join()
      this.handleFieldChanged(brandArr, { type: 'brandSelect', prop, label: '合作品牌' })
    },
    getValidate () {
      return new Promise((resolve, reject) => {
        this.$refs[this.refName].validate((valid, object) => {
          resolve(_.isEmpty(object) ? null : object)
        })
      })
    },
    validate () {
      this.$refs[this.refName].validate((valid) => {
        this.valid = valid
        if (valid) {
          // alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    getData () {
      return this.formData
      // return {
      //   valid: this.valid,
      //   formData: this.formData
      // }
    },
    handleClickButton (item, field) {
      const methodByType = {
        'view': () => this.handleViewCategoryInfo(field),
        'edit': this.handleEditCategoryInfo
      }
      const runMethod = methodByType[item.key] || (() => {});
      runMethod();
    },
    handleViewCategoryInfo (field) {
      this.viewDialog.visible = true;
      this.viewDialog.list = this.formData[field.prop] || [];
    },
    handleEditCategoryInfo () {
      this.businessCategory.visible = true;
    },
    getCheckedCategory ({ source }) {
      console.log('经营品类 manageCategory 修改 :>>', source)
      this.formData.manageCategory = source;
      this.handleFieldChanged(source, { type: 'categorySelect', prop: 'manageCategory', label: '经营品类' })
    },
    handleColseDialog () {
      this.viewDialog.visible = false;
    },
    operationObj (field) {
      const obj = this.operation && this.operation.find(i => i.field === field)
      return obj
    },
    isHighlight (field) {
      return this.operation && this.operation.find(i => i.field === field)
    }
  },
}
</script>

<style lang="less">
.number-input-align-left .el-input-number .el-input__inner {
  text-align: start !important;
}
.show_category_tags_wrap {
  min-height: 300px;
}
.supplier-info-form {
  .highlight {
    .el-input, .el-textarea {
      box-shadow: 0 0 2px red;
    }
    .highlight-hint {
      color: red;
    }
  }
  .el-form-item__content .el-input-group {
    vertical-align: initial
  }
  .delete-icon {
    color: red;
    cursor: pointer;
  }
}
</style>
